package controller

import (
	"encoding/json"
	"fmt"
	"ginfast/api/weixin/service"
	"net/http"
)

const (
	code2Session   = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
	getAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
	getPaidUnionId = "https://api.weixin.qq.com/wxa/getpaidunionid?access_token=%s&openid=%s"
)

func httpGet(url string, obj interface{}) error {
	resp, err := http.DefaultClient.Get(url)
	if err != nil {
		return err
	}
	err = json.NewDecoder(resp.Body).Decode(obj)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	return nil
}

type Code2Session struct {
	OpenId     string `json:"openid"`      // 用户唯一标识
	Sessionkey string `json:"session_key"` // 会话密钥
	UnionId    string `json:"unionid"`     // 用户在开放平台的唯一标识符，在满足 UnionID 下发条件的情况下会返回，详见 UnionID 机制说明。
	ErrCode    int    `json:"errcode"`     // 错误码
	ErrMsg     string `json:"errMsg"`      // 错误信息
}

// AuthCode2Session 获取openid
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
func AuthCode2Session(code string) (*Code2Session, error) {
	app, err := service.Config.App()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf(code2Session, app.AppID, app.AppSecret, code)
	obj := &Code2Session{}
	err = httpGet(url, obj)
	return obj, err
}

type AccessToken struct {
	AccessToken string `json:"access_token"` // 获取到的凭证
	Sessionkey  int    `json:"expires_in"`   // 凭证有效时间，单位：秒。目前是7200秒之内的值。
	Errcode     int    `json:"errcode"`      //错误码
	ErrMsg      string `json:"errMsg"`       //错误信息
}

// AuthGetAccessToken
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
func AuthGetAccessToken(appid, secret string) (*AccessToken, error) {
	app, err := service.Config.App()
	if err != nil {
		return nil, err
	}
	url := fmt.Sprintf(getAccessToken, app.AppID, app.AppSecret)
	obj := &AccessToken{}
	err = httpGet(url, obj)
	return obj, err
}

// AuthGetPaidUnionId
// https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/user-info/auth.getPaidUnionId.html
func AuthGetPaidUnionId(accessToken, openid string, obj interface{}) error {
	url := fmt.Sprintf(getPaidUnionId, accessToken, openid)
	return httpGet(url, obj)
}
